package com.example.video.common.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.video.admin_server.entity.SysRole;
import com.example.video.admin_server.entity.SysUser;
import com.example.video.admin_server.mapper.SysRoleMapper;
import com.example.video.admin_server.service.ISysUserService;
import com.example.video.common.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : yj
 */
@Component
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        SysUser one = iSysUserService.getOne(new QueryWrapper<>(sysUser));
        if (one == null){
            throw new UsernameNotFoundException("用户或者密码错误");
        }
        List<SysRole> roleList = sysRoleMapper.findByUserId(one.getId(), Constant.Status.ENABLE.value);
        UserDetails build = new SysUserDetails(one, roleList);
        return build;
    }
}
